# MephistoFlickrAjax

require File.join(RAILS_ROOT, "lib", "mephisto", "routing.rb")

class MacgalleryController < ActionController::Base
  def index
    result = ""

    pics = find_pictures
    pics.each do |pic|
      attrs = {:src => pic.send(params[:format].to_sym), :title => pic.title} 
      attrs[:width] = params[:width] unless params[:width].blank?
      attrs[:height] = params[:height] unless params[:height].blank?
      attr_str = []
      attrs.each do |k,v|
        attr_str << "#{k}=\"#{v}\""
      end
      result << "<a href='#{pic.link}'><img #{attr_str.join(" ")}></a>"
    end

    render :inline => result
  end
  protected
    def find_pictures
      MacGalleryAggregation.new(feed_url).choose(count)
    end
    
    def feed_url
      params[:feed]
    end

    def count
      params[:count].to_i
    end
    
    def fmt
      params[:format]
    end
end

module Mephisto
  class Routing
    class << self
      def connect_with_with_macgallery(map)
        map.connect 'macgallery', :controller => 'macgallery', :action => 'index'
        connect_with_without_macgallery(map)
      end
      alias_method_chain :connect_with, :macgallery
    end
  end
end

class MacGallery < Liquid::Block
  def initialize(markup, tokens)
    super 
    @attributes = {
      :feed => 'http://gallery.mac.com/dsboulder/?webdav-method=truthget&feedfmt=photocastrss',
      :count => 6,
      :format => "square"
      }
      
    markup.scan(Liquid::TagAttributes) do |key, value|
      @attributes[key.to_sym] = value
    end
  end
  
  def render(context)
    h = {:width => @attributes[:width], :height => @attributes[:height], :feed => @attributes[:feed], :count => @attributes[:count], :format => @attributes[:format]}
    query_str = []
    h.each do |k,v|
      query_str << "#{k}=#{CGI.escape(v.to_s)}" if v
    end
    <<-EOF
      <div id="macgallery_photos"></div>
      <script type="text/javascript">
        new Ajax.Updater("macgallery_photos", "/macgallery?#{query_str.join("&")}")
      </script>
    EOF
  end
end

Liquid::Template.register_tag('macgallery', MacGallery)